#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gw_cmd_tool
import gw_file_system
import logging
import platform
from hashlib import md5
import MySQLdb
import json
import shutil

FORMAT = '%(asctime)-15s ====> %(message)s '
logging.basicConfig(format=FORMAT, level=0)
logger = logging.getLogger('gw_main')

DB_ADDR = "42.62.78.40"
DB_USER_NAME = "wangbing"
DB_USER_PASSWORD = "wangbing"

FILE_PREFIX = "pc_pack_plugin_20150506_"
FILE_URL = "http://7vznh7.com1.z0.glb.clouddn.com/"
SRC_PATH = "D:/gitlab/Client_Source/Win32/Release"
ACCESS_KEY = "B81Gsvry2StqKVE3txS-7v9GBBfqykC9zhebmxnW"
SECRET_KEY = "YEZJuYcdeF7vRvzffxpopAVR-jMPZg9pZ-4IKTVW"
BUCKET = "hjrstatic"

def main():
    #get_update_info()
    file_list = get_file_list()
    createQiNiuSrcPath(file_list)
    createQiNiuJson()
    if upload_niqiu():
        file_md5_list = get_file_md5(file_list)
        update_db(file_md5_list)
        #get_install_package()
    return

#更新库
def get_update_info():
    cmd = "svn update "+SRC_PATH
    gw_cmd_tool.exec_cmd(cmd)
    return

#需要升级的文件列表
def get_file_list():
    need_update_file_list = [
        #{"filename":"AppLoader.exe","locate":"apploader/AppLoader.exe","url":FILE_URL+FILE_PREFIX+"AppLoader.exe","file_path":SRC_PATH+"/AppLoader.exe","version":"1.0.0","md5":""},
        #{"filename":"auto_package.exe","locate":"auto_package.exe","url":FILE_URL+FILE_PREFIX+"auto_package.exe","file_path":SRC_PATH+"/auto_package.exe","version":"1.0.0","md5":""},
        #{"filename":"core.exe","locate":"tool/Script/core.exe","url":FILE_URL+FILE_PREFIX+"core.exe","file_path":SRC_PATH+"/tool/Script/core.exe","version":"1.0.0","md5":""},
        {"filename":"library.zip","locate":"tool/py/library.zip","url":FILE_URL+FILE_PREFIX+"library.zip","file_path":SRC_PATH+"/library.zip","version":"1.0.0","md5":""},
        #{"filename":"KillResDul.jar","locate":"tool/tool/win/KillResDul.jar","url":FILE_URL+FILE_PREFIX+"KillResDul.jar","file_path":SRC_PATH+"/tool/tool/win/KillResDul.jar","version":"1.0.0","md5":""}
        {"filename":"apktool.jar","locate":"tool/thirdpart/windows/apktool.jar","url":FILE_URL+FILE_PREFIX+"apktool.jar","file_path":SRC_PATH+"/apktool.jar","version":"1.0.0","md5":""},

    ]
    return need_update_file_list

def get_file_md5(file_list):
    list = []
    for file in file_list:
        #logger.info(file["filename"])
        file["md5"] = md5_file(file["file_path"])
        list.append(file)
    return list

#上传七牛
def upload_niqiu():
    if platform.system() == "Windows":
        qrsync = gw_file_system.get_full_path("qiniu/qrsync.exe")
        json = gw_file_system.get_full_path("qiniu/conf.json")
        tool = qrsync+" "+json
    if platform.system() == "Linux":
        tool = ''
    gw_cmd_tool.exec_cmd(tool)
    return True

#更新数据库
def update_db(file_list):
    db = MySQLdb.connect(DB_ADDR,DB_USER_NAME,DB_USER_PASSWORD,"anyminisdk" )
    c = db.cursor()
    c.execute('delete from tool_version_control')

    for r in file_list:
        sql_data = "INSERT INTO tool_version_control(md5,version,file,url)VALUES "
        sql_data +="('"+r['md5']+"','"+r['version']+"','"+r['locate']+"','"+r['url']+"')"
        c.execute(sql_data)

    db.commit()
    c.close()
    db.close()
    return

#制作安装包
def get_install_package():
    logger.info("maek installpackage")

    tool = gw_file_system.get_full_path("Inno_Setup5/ISCC.exe")+" "+gw_file_system.get_full_path('UninstallCode.iss')
    gw_cmd_tool.exec_cmd(tool)
    return

#计算文件的md5
def md5_file(name):
    logger.info(name)
    m = md5()
    a_file = open(name, 'rb')
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()

#创建上传七牛所需要的JSON文件
def createQiNiuJson():
    dict = {}
    dict["src"] =  gw_file_system.get_cur_dir()+"/update_files"
    logger.info(dict["src"])
    dict["dest"] = "qiniu:access_key="+ACCESS_KEY+"&secret_key="+SECRET_KEY+"&bucket="+BUCKET+"&key_prefix="+FILE_PREFIX
    dict["deletable"] = 0
    dict["debug_level"] = 1
    #list =[dict]
    json_string = json.dumps(dict)
    fp = open("qiniu/conf.json","w")
    fp.writelines(json_string)
    return

#把要上传七牛的文件copy到单独的文件夹
def createQiNiuSrcPath(file_list):
    dst_dir = "update_files/"
    for file in file_list:
        shutil.copyfile(file["file_path"],dst_dir+file["filename"])
    return

if __name__=='__main__':
    main()
